import React, { useState } from 'react'
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Divider,
  Row,
  Col,
  TreeSelect,
  Typography,
  Descriptions
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  ApartmentOutlined,
  TeamOutlined,
  SafetyCertificateOutlined,
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { Option } = Select
const { TextArea } = Input

// 模拟部门数据
const departmentData = [
  {
    id: 1,
    name: '总公司',
    children: [
      {
        id: 2,
        name: '技术研发中心',
        children: [
          { id: 3, name: '前端开发部' },
          { id: 4, name: '后端开发部' },
          { id: 5, name: '测试部' }
        ]
      },
      {
        id: 6,
        name: '市场运营中心',
        children: [
          { id: 7, name: '市场部' },
          { id: 8, name: '运营部' }
        ]
      },
      {
        id: 9,
        name: '行政管理中心',
        children: [
          { id: 10, name: '人力资源部' },
          { id: 11, name: '财务部' }
        ]
      }
    ]
  }
]

// 模拟角色数据
const roleData = [
  { id: 1, name: '超级管理员', code: 'super_admin' },
  { id: 2, name: '部门管理员', code: 'dept_admin' },
  { id: 3, name: '普通员工', code: 'staff' },
  { id: 4, name: '人事专员', code: 'hr' },
  { id: 5, name: '财务专员', code: 'finance' }
]

// 模拟岗位数据
const initialPositions = [
  {
    id: 1,
    name: '前端开发工程师',
    code: 'FE_ENGINEER',
    departmentId: 3,
    departmentName: '前端开发部',
    roles: [1, 3],
    status: true,
    description: '负责前端开发工作',
    createTime: '2023-01-15 10:30:00'
  },
  {
    id: 2,
    name: '后端开发工程师',
    code: 'BE_ENGINEER',
    departmentId: 4,
    departmentName: '后端开发部',
    roles: [1, 3],
    status: true,
    description: '负责后端开发工作',
    createTime: '2023-02-10 14:20:00'
  },
  {
    id: 3,
    name: '测试工程师',
    code: 'QA_ENGINEER',
    departmentId: 5,
    departmentName: '测试部',
    roles: [3],
    status: true,
    description: '负责软件测试工作',
    createTime: '2023-03-05 09:15:00'
  },
  {
    id: 4,
    name: '市场经理',
    code: 'MARKET_MANAGER',
    departmentId: 7,
    departmentName: '市场部',
    roles: [2, 3],
    status: true,
    description: '负责市场推广工作',
    createTime: '2023-04-12 16:45:00'
  },
  {
    id: 5,
    name: '人力资源专员',
    code: 'HR_SPECIALIST',
    departmentId: 10,
    departmentName: '人力资源部',
    roles: [4],
    status: true,
    description: '负责人力资源管理工作',
    createTime: '2023-05-20 11:30:00'
  }
]

const PositionManagement = () => {
  const [positions, setPositions] = useState(initialPositions)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingPosition, setEditingPosition] = useState(null)
  const [selectedPosition, setSelectedPosition] = useState(null)
  const [form] = Form.useForm()

  // 部门树形数据转换
  const convertToTreeData = data => {
    return data.map(item => ({
      title: item.name,
      value: item.id,
      key: item.id,
      children: item.children ? convertToTreeData(item.children) : []
    }))
  }

  const departmentTreeData = convertToTreeData(departmentData)

  // 获取部门名称
  const getDepartmentName = id => {
    const findDepartment = (data, id) => {
      for (const item of data) {
        if (item.id === id) return item.name
        if (item.children) {
          const name = findDepartment(item.children, id)
          if (name) return name
        }
      }
      return null
    }
    return findDepartment(departmentData, id) || '未知部门'
  }

  // 获取角色名称
  const getRoleNames = roleIds => {
    return roleIds
      .map(id => {
        const role = roleData.find(r => r.id === id)
        return role ? role.name : '未知角色'
      })
      .join(', ')
  }

  // 获取状态文本
  const getStatusText = status => {
    return status ? '启用' : '禁用'
  }

  // 获取状态颜色
  const getStatusColor = status => {
    return status ? 'green' : 'red'
  }

  // 岗位表格列
  const columns = [
    {
      title: '岗位名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <span>
          <UserOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          {text}
        </span>
      )
    },
    {
      title: '岗位编码',
      dataIndex: 'code',
      key: 'code',
      render: text => <Tag color='blue'>{text}</Tag>
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      key: 'departmentName',
      render: (text, record) => (
        <span>
          <ApartmentOutlined style={{ marginRight: 8, color: '#52c41a' }} />
          {text}
        </span>
      )
    },
    {
      title: '关联角色',
      dataIndex: 'roles',
      key: 'roles',
      render: roleIds => (
        <span>
          <TeamOutlined style={{ marginRight: 8, color: '#fa8c16' }} />
          {getRoleNames(roleIds)}
        </span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size='middle'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title='确定要删除这个岗位吗？'
            onConfirm={() => handleDelete(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 显示新增模态框
  const showModal = () => {
    setEditingPosition(null)
    form.resetFields()
    setModalVisible(true)
  }

  // 显示编辑模态框
  const handleEdit = position => {
    setEditingPosition(position)
    form.setFieldsValue({
      ...position,
      departmentId: position.departmentId.toString()
    })
    setModalVisible(true)
  }

  // 删除岗位
  const handleDelete = id => {
    setPositions(positions.filter(item => item.id !== id))
    message.success('岗位删除成功')
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingPosition) {
      // 编辑岗位
      const updatedPositions = positions.map(item => {
        if (item.id === editingPosition.id) {
          return {
            ...item,
            ...values,
            departmentId: parseInt(values.departmentId),
            departmentName: getDepartmentName(parseInt(values.departmentId)),
            updateTime: new Date().toLocaleString()
          }
        }
        return item
      })
      setPositions(updatedPositions)
      message.success('岗位更新成功')
    } else {
      // 新增岗位
      const newPosition = {
        id: Math.max(...positions.map(p => p.id)) + 1,
        ...values,
        departmentId: parseInt(values.departmentId),
        departmentName: getDepartmentName(parseInt(values.departmentId)),
        roles: values.roles || [],
        createTime: new Date().toLocaleString()
      }
      setPositions([...positions, newPosition])
      message.success('岗位创建成功')
    }
    setModalVisible(false)
  }

  return (
    <div className='position-management'>
      <Card>
        <div
          style={{
            marginBottom: 16,
            display: 'flex',
            justifyContent: 'space-between'
          }}
        >
          <Title level={4} style={{ margin: 0 }}>
            <SafetyCertificateOutlined style={{ marginRight: 12 }} />
            岗位管理
          </Title>
          <Button type='primary' icon={<PlusOutlined />} onClick={showModal}>
            新增岗位
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={positions}
          rowKey='id'
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`
          }}
          onRow={record => ({
            onClick: () => setSelectedPosition(record)
          })}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: selectedPosition ? [selectedPosition.id] : [],
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedPosition(selectedRows[0] || null)
            }
          }}
        />

        {selectedPosition && (
          <div style={{ marginTop: 24 }}>
            <Descriptions title='岗位详情' bordered column={2}>
              <Descriptions.Item label='岗位名称'>
                {selectedPosition.name}
              </Descriptions.Item>
              <Descriptions.Item label='岗位编码'>
                <Tag color='blue'>{selectedPosition.code}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label='所属部门'>
                <Space>
                  <ApartmentOutlined />
                  {selectedPosition.departmentName}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label='关联角色'>
                <Space>
                  <TeamOutlined />
                  {getRoleNames(selectedPosition.roles)}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label='状态'>
                <Tag color={getStatusColor(selectedPosition.status)}>
                  {getStatusText(selectedPosition.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label='创建时间'>
                {selectedPosition.createTime}
              </Descriptions.Item>
              <Descriptions.Item label='岗位描述' span={2}>
                {selectedPosition.description || '暂无描述'}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Card>

      {/* 新增/编辑岗位模态框 */}
      <Modal
        title={editingPosition ? '编辑岗位' : '新增岗位'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='name'
                label='岗位名称'
                rules={[{ required: true, message: '请输入岗位名称' }]}
              >
                <Input placeholder='请输入岗位名称' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='code'
                label='岗位编码'
                rules={[{ required: true, message: '请输入岗位编码' }]}
              >
                <Input placeholder='请输入岗位编码' />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name='departmentId'
            label='所属部门'
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <TreeSelect
              treeData={departmentTreeData}
              placeholder='请选择所属部门'
              treeDefaultExpandAll
              showSearch
              treeNodeFilterProp='title'
            />
          </Form.Item>

          <Form.Item name='roles' label='关联角色'>
            <Select
              mode='multiple'
              placeholder='请选择关联角色'
              optionLabelProp='label'
            >
              {roleData.map(role => (
                <Option key={role.id} value={role.id} label={role.name}>
                  <Space>
                    <TeamOutlined />
                    {role.name} ({role.code})
                  </Space>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name='status' label='状态' valuePropName='checked'>
            <Switch
              checkedChildren='启用'
              unCheckedChildren='禁用'
              defaultChecked
            />
          </Form.Item>

          <Form.Item name='description' label='岗位描述'>
            <TextArea rows={4} placeholder='请输入岗位描述' />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingPosition ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default PositionManagement
